<?php

namespace App\Traits;


use App\Common\Log;
use XWX\Common\H;

trait TraitExcel
{
    /**
     * 处理特殊字符
     *
     * @param $str
     * @param $prefix `123456789
     * @return mixed
     */
    function ExportSetCol__CSV($str, $prefix = null)
    {
        $str = str_replace(',', '，', $str);
        $str = str_replace("\n", '\\n', $str);
        $str = str_replace("\"", '', $str);

        if ($prefix != null)
        {
            $str = $prefix . $str;
        }

        return $str;
    }


    /**
     * 设置导出请求头
     *
     * @param null $fileName
     */
    public function ExportCsvHead($fileName = null)
    {
        if (H::funcStrIsNullOrEmpty($fileName))
        {
            $fileName = time() . '.csv';
        }


        $this->response()->getSwooleResponse()->header('Pragma', 'public');
        $this->response()->getSwooleResponse()->header('Expires', '0');
        $this->response()->getSwooleResponse()->header('Content-Type', 'application/vnd.ms-excel');
        $this->response()->getSwooleResponse()->header('Content-Disposition', "attachment;filename={$fileName}");
        $this->response()->getSwooleResponse()->header('Cache-Control', 'max-age=0');
    }

    /**
     * 添加导出数据
     *
     * @param array $data
     * @throws \Exception
     */
    public function ExportCsvAddData(array & $data)
    {
        Log::funcLog(__METHOD__, 'BEGIN');


        foreach ($data as $k => $row)
        {
            $row_str = '';
            foreach ($row as $col)
            {
                if ($k != 0)
                {
                    //表头不需要处理
                    $col = $this->ExportSetCol__CSV($col);
                }

                //CSV的Excel支持GBK编码，一定要转换，否则乱码
//                $row_str .= iconv('utf-8', 'gbk//IGNORE', $col) . ",";
                $row_str .= mb_convert_encoding($col, "GBK", "auto") . ",";
            }

            $this->response()->getSwooleResponse()->write($row_str . PHP_EOL);
        }

        Log::funcLog(__METHOD__, 'END');
    }


    /**
     * 制作导出数据
     *
     * @param array $table_head
     * @param array $table_data
     * @param bool $exclude_head 是否过滤$table_head
     * @return array
     */
    public function ExportSetData(array & $table_head, array & $table_data, $exclude_head = false)
    {
        $data = [];

        if (!$exclude_head)
        {
            //表头
            $head = [];
            foreach ($table_head as $key => $value)
            {
                array_push($head, '"' . $value . '"');
            }

            array_push($data, $head);
        }


        //表内容
        foreach ($table_data as $row_data)
        {
            $item = [];
            foreach ($table_head as $k => $v)
            {
                if (array_key_exists($k, $row_data))
                {
                    array_push($item, (string)$row_data[$k]);
                }
                else
                {
                    //没key，val为空
                    array_push($item, '');
                }
            }

            array_push($data, $item);
        }


        return $data;
    }

}